<template>
	<el-date-picker v-model="date" type="datetimerange" unlink-panels range-separator="-" start-placeholder="开始日期"
		end-placeholder="结束日期" :shortcuts="shortcuts" :value-format="format" @change="onDatePickerChange"></el-date-picker>
</template>

<script setup>
import { ref } from "vue"

const props = defineProps({
	start: {
		type: [String, Number],
		default: "",
	},
	end: {
		type: [String, Number],
		default: "",
	},
	format: {
		type: String,
		default: "YYYY-MM-DD hh:mm:ss",
	},
	type: {
		type: String,
		default: "string",
	},
	modelValue: {
		type: [Array],
		default: () => [],
	},
})

const emits = defineEmits(["change", "update:start", "update:end", "update:modelValue"])

const date = ref([])
const shortcuts = [
	{
		text: "最近一周",
		value() {
			const end = new Date()
			const start = new Date()
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
			return [start, end]
		},
	},
	{
		text: "最近一个月",
		value() {
			const end = new Date()
			const start = new Date()
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
			return [start, end]
		},
	},
	{
		text: "最近三个月",
		value() {
			const end = new Date()
			const start = new Date()
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
			return [start, end]
		},
	},
]

function onDatePickerChange(value) {
	const [start, end] = value
	if (props.type === "string") {
		emits("update:start", start)
		emits("update:end", end)
		emits("update:modelValue", [start, end])
	} else if (props.type === "timestamp") {
		emits("update:start", +new Date(start))
		emits("update:end", +new Date(end))
		emits("update:modelValue", [+new Date(start), +new Date(end)])
	} else if (props.type === "date") {
		emits("update:start", new Date(start))
		emits("update:end", new Date(end))
		emits("update:modelValue", [new Date(start), new Date(end)])
	}
	emits("change", value)
}
</script>

<style lang="scss" scoped></style>
